import React from 'react';
import '../../style.less';
import './home.less';
import {Spin} from 'antd';
import superagent from 'superagent';
import jsonp from 'superagent-jsonp';
import echarts from 'echarts';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import 'echarts/theme/dark';
import Draggable from 'react-draggable';

function newline(option, number, axis) {
    option[axis]['axisLabel'] = {
        interval: 0,
        formatter: function (params) {
            var newParamsName = "";
            var paramsNameNumber = params.length;
            var provideNumber = number;
            var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
            if (paramsNameNumber > provideNumber) {
                for (var p = 0; p < rowNumber; p++) {
                    var tempStr = "";
                    var start = p * provideNumber;
                    var end = start + provideNumber;
                    if (p == rowNumber - 1) {
                        tempStr = params.substring(start, paramsNameNumber);
                    } else {
                        tempStr = params.substring(start, end) + "\n";
                    }
                    newParamsName += tempStr;
                }
            } else {
                newParamsName = params;
            }
            return newParamsName
        }
    }
    return option;
}

function max(prev, next) {
    return Math.max(prev, next);
}

function min(prev, next) {
    return Math.min(prev, next);
}

let mapStyle = {height: 800, width: 460};
const position = [32.04, 118.78];


let titleStyle = {
    color: '#00e4ff',
    fontSize: 16
};

let allData;
let myChart,//降雨信息
    pumpChart,//泵站左
    pumpRightChart,//泵站右
    floodPointChart,//积淹点
    floodPointRightChart,//大饼
    waterLevelChart,//长江水位流量
    alertCircleChart,//水库总数饼图
    reservoirChart;//水库水位

let layerGroup;

function getData(obj, map) {
    let getAllPos = JSON.parse(localStorage.getItem('allPos'))

    for (let pos in getAllPos) {
        if (getAllPos[pos].left) {
            document.getElementById(pos).style.left = getAllPos[pos].left + "px";
            document.getElementById(pos).style.top = getAllPos[pos].top + "px";
        }
    }
    superagent
        .get(window.httpAddress + '/njfx/getScreenData!FLOOD')
        .end(function (err, res) {
            allData = JSON.parse(res.text)

            if (layerGroup) {
                layerGroup.clearLayers();
            } else {
                layerGroup = L.layerGroup({});
            }


            let marker1, marker2, marker3, marker4
            //显示警戒
            let warnPoint = allData.alert;
            //雨量
            for (let w1 in warnPoint.rain) {
                marker1 = L.marker([warnPoint.rain[w1].latd, warnPoint.rain[w1].lgtd], {icon: icon1}).bindPopup(warnPoint.rain[w1].stnm + ': ' + warnPoint.rain[w1].value);
                layerGroup.addLayer(marker1).addTo(map);
            }
            //河道
            for (let w2 in warnPoint.river) {
                marker2 = L.marker([warnPoint.river[w2].latd, warnPoint.river[w2].lgtd], {icon: icon2}).bindPopup(warnPoint.river[w2].stnm + ': ' + warnPoint.river[w2].value);
                layerGroup.addLayer(marker2).addTo(map);
            }

            //水库
            for (let w3 in warnPoint.rsvr.mRsvr) {
                marker3 = L.marker([warnPoint.rsvr.mRsvr[w3].latd, warnPoint.rsvr.mRsvr[w3].lgtd], {icon: icon3}).bindPopup(warnPoint.rsvr.mRsvr[w3].stnm + ': ' + warnPoint.rsvr.mRsvr[w3].value);
                layerGroup.addLayer(marker3).addTo(map);
            }
            //积水
            for (let w4 in warnPoint.flood) {
                marker4 = L.marker([warnPoint.flood[w4].latd, warnPoint.flood[w4].lgtd], {icon: icon4}).bindPopup(warnPoint.flood[w4].stnm + ': ' + warnPoint.flood[w4].value);
                layerGroup.addLayer(marker4).addTo(map);
            }


            obj.setState({
                loading: false,
                isoData: allData.img,
                channelData: allData.impRiver,
                emergency: allData.response,
                weather: allData.weather,
                njRain: allData.njRain
            })
            if (myChart) {

            } else {
                //降雨信息
                myChart = echarts.init(document.getElementById('rain'), 'dark');
                //机泵流量统计
                pumpChart = echarts.init(document.getElementById('pump'), 'dark');
                pumpRightChart = echarts.init(document.getElementById('pumpRight'), 'dark');
                //积淹点
                floodPointChart = echarts.init(document.getElementById('floodPoint'), 'dark');
                //积淹点大饼
                floodPointRightChart = echarts.init(document.getElementById('floodPointRight'), 'dark');
                //长江水位流量
                waterLevelChart = echarts.init(document.getElementById('waterLevel'), 'dark');
                //水库水位
                reservoirChart = echarts.init(document.getElementById('reservoir'), 'dark');
                //水库总数饼图
                alertCircleChart = echarts.init(document.getElementById('alertCircle'), 'dark');


            }
            //降雨信息
            let rainYData = [], rainXData = [], rainMostData = [], rainMarkPoint = [],
                nowDistRrain = allData.distRain.reverse()
            for (let i in nowDistRrain) {
                let rainArea = nowDistRrain[i].CITY.replace(/区/, "");
                rainYData.push(rainArea);
                rainXData.push(nowDistRrain[i].VALUE);
                rainMostData.push(nowDistRrain[i].maxValue);
                if (nowDistRrain[i].maxValue > 0) {
                    rainMarkPoint.push({
                        name: nowDistRrain[i].VALUE,
                        value: allData.distRain[i].maxSta,
                        coord: [allData.distRain[i].maxValue, Number(i)]
                    })
                }
            }
            let myOption = {
                title: {
                    text: '各区降雨',
                    left: 'center',
                    textStyle: titleStyle
                },
                backgroundColor: "transparent",
                legend: {
                    bottom: '0',
                    data: ['3日面平均雨量', '最大降雨点']
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b} : {c}'
                },
                xAxis: {
                    name: "(mm)",
                    type: 'value',
                    boundaryGap: ['0', '20%']
                },
                yAxis: {
                    name: "县区(名称)",
                    data: rainYData
                },
                series: [
                    {
                        name: '3日面平均雨量',
                        type: 'bar',
                        data: rainXData,
                        label: {
                            normal: {
                                show: true,
                                position: 'right',
                            }
                        },
                        itemStyle: {
                            normal: {
                                color: "#99ffff"
                            }
                        },
                    },
                    {
                        name: '最大降雨点',
                        type: 'bar',
                        data: rainMostData,
                        label: {
                            normal: {
                                show: true,
                                position: 'right'
                            }
                        },
                        itemStyle: {
                            normal: {
                                color: "#4d7dff"
                            }
                        },
                        markPoint: {
                            symbolRotate: 270,
                            symbolSize: 50,
                            symbolOffset: [26, 0],
                            label: {
                                normal: {
                                    show: true,
                                    position: [16, 10],
                                    formatter: '{c}'
                                }

                            },
                            data: rainMarkPoint
                        },
                    }
                ]
            }
            myChart.setOption(myOption);

            //机泵流量统计
            let pumpData = allData.gq;
            let pumpOption = {
                backgroundColor: '',
                title: {
                    text: "实时流量 " + pumpData[0].aFlow + "m³/s",
                    left: 'center',
                    textStyle: titleStyle
                },
                tooltip: {
                    formatter: "{a} <br/>{b} : {c}台"
                },
                series: [
                    {
                        radius: 90,
                        endAngle: 0,
                        startAngle: 180,
                        center: ['50%', '90%'],
                        min: 0,
                        max: pumpData[0].allCnt,
                        splitNumber: 3,
                        name: '启用台数',
                        type: 'gauge',
                        axisLine: {            // 坐标轴线
                            lineStyle: {       // 属性lineStyle控制线条样式
                                color: [[0.09, 'lime'], [0.82, '#1e90ff'], [1, '#ff4500']],
                                width: 3,
                                shadowColor: '#fff', //默认透明
                                shadowBlur: 10
                            }
                        },
                        axisLabel: {            // 坐标轴小标记
                            textStyle: {       // 属性lineStyle控制线条样式
                                fontWeight: 'bolder',
                                color: '#fff',
                                shadowColor: '#fff', //默认透明
                                shadowBlur: 10
                            }
                        },
                        axisTick: {            // 坐标轴小标记
                            length: 15,        // 属性length控制线长
                            lineStyle: {       // 属性lineStyle控制线条样式
                                color: 'auto',
                                shadowColor: '#fff', //默认透明
                                shadowBlur: 10
                            }
                        },
                        detail: {
                            width: 20,
                            height: 20,
                            offsetCenter: ['0', '-28'],       // x, y，单位px
                            textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                                color: '#fff',
                                fontSize: 18
                            }
                        },
                        data: [{value: pumpData[0].rtCnt}]
                    }
                ]

            };

            pumpChart.setOption(pumpOption)

            document.getElementById("pumpP").innerHTML = pumpData[0].hnnm;

            let pumpRightOption = {
                backgroundColor: '',
                title: {
                    text: "实时流量 " + pumpData[1].aFlow + "m³/s",
                    left: 'center',
                    textStyle: titleStyle
                },
                tooltip: {
                    formatter: "{a} <br/>{b} : {c}台"
                },
                series: [
                    {
                        radius: 90,
                        endAngle: 0,
                        startAngle: 180,
                        center: ['50%', '90%'],
                        min: 0,
                        max: pumpData[1].allCnt,
                        splitNumber: 2,
                        name: '启用台数',
                        type: 'gauge',
                        axisLine: {            // 坐标轴线
                            lineStyle: {       // 属性lineStyle控制线条样式
                                color: [[0.09, 'lime'], [0.82, '#1e90ff'], [1, '#ff4500']],
                                width: 3,
                                shadowColor: '#fff', //默认透明
                                shadowBlur: 10
                            }
                        },
                        axisLabel: {            // 坐标轴小标记
                            textStyle: {       // 属性lineStyle控制线条样式
                                fontWeight: 'bolder',
                                color: '#fff',
                                shadowColor: '#fff', //默认透明
                                shadowBlur: 10
                            }
                        },
                        axisTick: {            // 坐标轴小标记
                            length: 15,        // 属性length控制线长
                            lineStyle: {       // 属性lineStyle控制线条样式
                                color: 'auto',
                                shadowColor: '#fff', //默认透明
                                shadowBlur: 10
                            }
                        },
                        detail: {
                            width: 20,
                            height: 20,
                            offsetCenter: ['0', '-28'],       // x, y，单位px
                            textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                                color: '#fff',
                                fontSize: 18
                            }
                        },
                        data: [{value: pumpData[1].rtCnt}]
                    }
                ]

            };


            pumpRightChart.setOption(pumpRightOption)
            document.getElementById("pumpRightp").innerHTML = pumpData[1].hnnm;


            //积淹点信息
            let floodPointData = allData.flood.rtFlood.slice(0, 5), xFloodPointData = [], yFloodPointData = [];
            for (let x in floodPointData) {
                xFloodPointData.push(floodPointData[x].STNM.substring(0, 12))
                yFloodPointData.push(floodPointData[x].VALUE)
            }
            let floodPointOption = {

                backgroundColor: "transparent",
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b} : {c}'
                },
                xAxis: {
                    data: xFloodPointData,
                    axisLabel: {
                        color: "#000"
                    }
                },
                yAxis: {
                    name: "cm",
                    type: 'value'
                },
                series: [
                    {
                        name: '面平均雨量',
                        type: 'bar',
                        data: yFloodPointData,
                        label: {
                            normal: {
                                show: true,
                                position: 'top'
                            }
                        },
                    }
                ]
            }

            floodPointOption = newline(floodPointOption, 3, 'xAxis')

            floodPointChart.setOption(floodPointOption);


            //积淹点大饼
            let floodPointRightData = allData.flood.summary, floodPointRightDataArray = [],
                floodPointRightDataTitle = ['0-20', '20-30', '30-40', '40-50','>50' ];
            for (let y in floodPointRightData) {
                floodPointRightDataArray.push({value: floodPointRightData[y], name: floodPointRightDataTitle[y]})
            }
            let floodPointRightOption = {
                backgroundColor: "transparent",
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                title:{
                    text: "积水等级分布图",
                    textStyle: {
                        fontSize: 14
                    }
                },
                legend: {
                    orient: 'vertical',
                    left: 'right',
                    data: floodPointRightDataTitle
                },
                series: [
                    {
                        name: '积淹点',
                        type: 'pie',
                        radius: '50%',
                        center: ['45%', '60%'],
                        itemStyle: {
                            normal: {
                                color: function (val) {
                                    let name = val.name;
                                    if(name == '>50'){
                                        return "#ff3333";
                                    }else if(name == '40-50'){
                                        return "#ffcc00"
                                    }else if(name == '30-40'){
                                        return "#00c000"
                                    }else if(name == '20-30'){
                                        return "#007f80"
                                    }else{
                                        return "#99ffff";
                                    }


                                }
                            }
                        },
                        data: floodPointRightDataArray
                    }
                ]
            };

            floodPointRightChart.setOption(floodPointRightOption);

            //长江水位流量
            let datong = allData.datong, xaiguan = allData.xiaguan, ifMore, ifTall;
            Number(datong.compHisQ) > 0 ? ifMore = "多" : ifMore = "少";
            Number(xaiguan.compHis) > 0 ? ifTall = "高" : ifTall = "低";
            document.getElementById("waterLevelTop").innerHTML = `大通: 实时水位 <span>${datong.Z}m</span> 实时流量<span>${datong.Q / 10000}万m³/s</span> 较常年同期偏<span>${ifMore}${Math.abs(Number(datong.compHisQ))}%</span>`;
            document.getElementById("waterLevelBottom").innerHTML = `下关: 实时潮位 <span>${xaiguan.Z}m</span> 较常年同期偏<span>${ifTall}${Math.abs(Number(xaiguan.compHis))}m</span>`

            let datong1 = [], datong2 = [], xiaguanData1 = [], waterTl = [];
            for (let z in allData.datong.process) {
                waterTl.push(allData.datong.process[z].TM);
                datong1.push(allData.datong.process[z].Z);
                datong2.push(allData.datong.process[z].Q / 10000);
                xiaguanData1.push(allData.xiaguan.process[z].Z);
            }


            // console.log(datong1.concat(xiaguanData1).reduce(max))
            // console.log(datong1.concat(xiaguanData1).reduce(min))
            let waterLevelOption = {
                backgroundColor: "transparent",
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b} : {c}'
                },
                legend: {
                    bottom: '0',
                    data: ['大通水位', '大通流量', '下关潮位']
                },
                yAxis: [
                    {
                        type: 'value',
                        name: 'm',
                        min: Math.floor(datong1.concat(xiaguanData1).reduce(min) * .9),
                    },
                    {
                        type: 'value',
                        name: '万m³/s',
                        min: Math.floor(datong2.reduce(min) * .9)

                    }
                ],
                xAxis: {
                    data: waterTl
                },
                series: [
                    {
                        name: "大通水位",
                        type: "line",
                        data: datong1
                    },
                    {
                        name: "大通流量",
                        type: "line",
                        yAxisIndex: 1,
                        data: datong2,
                        itemStyle: {
                            normal: {
                                color: '#ffff00'
                            }
                        }
                    },
                    {
                        name: "下关潮位",
                        type: "line",
                        data: xiaguanData1,
                        itemStyle: {
                            normal: {
                                color: '#00c000'
                            }
                        }
                    }
                ]
            }

            waterLevelChart.setOption(waterLevelOption);


            //水库水位

            let reservoirData = allData.impRsvr, reservoirDatax = [], reservoirDatay = [], reservoirWarn = [];
            for (let xx in reservoirData) {
                reservoirDatax.push(reservoirData[xx].STNM.replace(/水库/,""));
                reservoirDatay.push(reservoirData[xx].Z);
                reservoirWarn.push(reservoirData[xx].WRZ);
            }
            let reservoirOption = {
                backgroundColor: "transparent",
                tooltip: {
                    trigger: 'item',
                    formatter: '{b} : {c}m<br />'
                },
                xAxis: {
                    data: reservoirDatax,

                },
                yAxis: {
                    name: "m",
                },
                series: [
                    {
                        name: "水库水位",
                        type: 'bar',
                        label: {
                            normal: {
                                show: true,
                                position: 'top'
                            }
                        },
                        itemStyle: {
                            normal: {
                                color: function (val) {
                                    if (val.value >= reservoirWarn[val.dataIndex]) {
                                        return "#fc9c13"
                                    } else {
                                        return "#17a6ca"
                                    }
                                }
                            }
                        },
                        data: reservoirDatay
                    }
                ]
            }

            let newReservoirOption = newline(reservoirOption, 2, 'xAxis')

            reservoirChart.setOption(newReservoirOption);

            //水库总数饼图
            let alertCircleData = allData.alert.rsvr, alertCircleArr = [];
            alertCircleArr.push({
                name: "超汛限水库",
                value: alertCircleData.alertNum
            })
            alertCircleArr.push({
                name: "正常水库",
                value: alertCircleData.total - alertCircleData.alertNum
            })
            let alertCircleOption = {
                backgroundColor: "transparent",

                series: [
                    {
                        name: '水库情况',
                        type: 'pie',
                        radius: '30%',
                        center: ['50%', '60%'],
                        label: {
                            normal: {
                                show: true,
                                position: 'right',
                                formatter: '{b}{c}座'
                            }
                        },
                        data: alertCircleArr

                    }
                ]
            };


            alertCircleChart.setOption(alertCircleOption)


        })

}

//等值面
class Isosurface extends React.Component {
    constructor(props) {
        super(props)
    }

    componentWillReceiveProps(nextProps) {
        // console.log(nextProps)
    }

    render() {
        let imgUrl, imgLel = this.props.info.lelve, levelGroup = [];
        if (this.props.info.success) {
            this.props.info.bg ? imgUrl = this.props.info.imgurl.replace(/http:\/\/10.32.224.49/, window.httpAddress) : true;
        } else {
            imgUrl = window.httpAddress + ":8181/isocreator/blnlib/njfx2.png";
        }
        for (let i in imgLel) {
            levelGroup.push(
                <div className="lvlItem" key={i}>
                    <span style={{background: imgLel[i].color}}></span>
                    {imgLel[i].value}
                </div>
            )
        }
        return (
            <div className="fl isosurface">
                <img src={imgUrl} alt=""/>
                <div className="lvlWrap">
                    {levelGroup}
                </div>
            </div>
        )
    }

}


//河道水位
class WaterChannel extends React.Component {
    constructor(props) {
        super(props);
    }

    componentWillReceiveProps(nextProps) {

    }

    render() {
        let waterInfo = [];
        for (let i in this.props.info) {
            if (i < 7) {
                waterInfo.push(
                    <tr key={i}>
                        <td className="waterInfo1">{this.props.info[i].STNM}</td>
                        <td>{this.props.info[i].Z}</td>
                        <td>{this.props.info[i].WRZ}</td>
                        <td>{this.props.info[i].HISHIGHEST}</td>
                        <td>{this.props.info[i].hisOrder}</td>
                    </tr>
                )
            }

        }
        return (
            <div className="waterChannel">
                {waterInfo ? (
                    <table>
                        <thead>
                        <tr>
                            <th>站点名称</th>
                            <th>实时水位(m)</th>
                            <th>警戒水位(m)</th>
                            <th>历史最高水位(m)</th>
                            <th>历史同期排名</th>
                        </tr>
                        </thead>
                        <tbody>
                        {waterInfo}
                        </tbody>
                    </table>
                ) : (
                    <div></div>
                )}

            </div>
        )
    }
}

//应急响应
class Emergency extends React.Component {
    constructor(props) {
        super(props);
    }

    componentWillReceiveProps(nextProps) {

    }

    render() {
        let emer1, emer2 = [], emergencySecond = []
        for (let i in this.props.info) {
            if (i == 0) {
                emer1 = this.props.info[i];
            } else {
                emer2.push(
                    <div className="fl" key={i}>
                        <img src={`images/emergency/${this.props.info[i].LEVEL}.png`} alt=""/>
                        <p>{this.props.info[i].STLC}</p>
                    </div>
                )
            }
        }

        return (
            <div className="emergencyContainerWrap">
                {emer1 ? (
                    <div className="emergencyContainer">
                        <div className="emergencyFirst">
                            <img src={`images/emergency/${emer1.LEVEL}.png`} alt=""/>
                            {emer1.STLC}
                        </div>
                        <div className="clearfix emergencySecond">
                            {emer2}
                        </div>
                    </div>
                ) : (
                    <div className="emergencyContainer"></div>
                )}

            </div>
        )
    }
}

//气象信息
let week = ["今天", "明天", "后天", "大后天"];

class Weather extends React.Component {
    constructor(props) {
        super(props);

    }

    componentWillReceiveProps(nextProps) {

    }

    render() {
        let weatherInfo = this.props.info, weatherArr = [];
        for (let i in weatherInfo) {
            if (i <= 3) {
                let temImg;
                weatherInfo ? temImg = "iconfont icon-" + weatherInfo[i].icon : true;
                weatherArr.push(
                    <div className="fl weatherItem" key={i}>
                        <div className="weatherTitle">{week[i]}</div>
                        <div className="textCenter weatherMid">
                            <p>
                                <i className={temImg}></i>
                            </p>

                            {weatherInfo[i].weather12h?weatherInfo[i].weather12h:"多云"}
                        </div>
                        <div className="textCenter weatherBottom">
                            {weatherInfo[i].minTemp24h}℃ / {weatherInfo[i].maxTemp24h}℃
                        </div>
                    </div>
                )
            }

        }
        return (
            <div className="mt10 weatherArea">
                {weatherInfo ? (
                    <div>
                        <div className="clearfix">
                            {weatherArr}
                        </div>
                        <div className="h24">

                        </div>
                        <div className="weatherSource">来源: 市气象局</div>
                    </div>


                ) : (
                    <div className="clearfix">
                    </div>
                )}
            </div>
        )
    }
}

//降雨信息上
class RainTop extends React.Component {
    constructor(props) {
        super(props);
    }

    componentWillReceiveProps(nextProps) {

    }

    render() {
        let rainTopData = this.props.info
        return (
            <div className="rainTop">

                {rainTopData ? (
                    <div>
                        <div className="clearfix textCenter selfGraphic">
                            <div className="fl rainTopItem">
                                <div className="rainh">
                                    {rainTopData.TVALUE}mm
                                </div>
                                今日降雨量
                            </div>
                            <div className="fl rainTopItem rainTopItemMid">
                                <div className="rainh">
                                    {rainTopData.YVALUE}mm
                                </div>
                                昨日降雨量
                            </div>
                            <div className="fr rainTopItem">
                                <div className="rainh">
                                    {rainTopData.TTVALUE}mm
                                </div>
                                三天降雨量
                            </div>
                        </div>
                        <div className="weatherSummary">
                            {rainTopData.summary}
                        </div>
                    </div>
                ) : (
                    <div></div>
                )}
            </div>


        )
    }
}


let allPos = {
    totalWrap: {},
    mainWrap: {},
    mapArea: {},
    waterLevelWrap: {},
    waterChannelWrap: {},
    pumpWrap: {},
    emergencyWrap: {},
    dangerWrap:{},
    reservoirWrap: {}
};
let map;

let icon1 = L.icon({
    iconUrl: 'images/legend/1.gif',
    iconSize: [20, 20],
});
let icon2 = L.icon({
    iconUrl: 'images/legend/2.gif',
    iconSize: [20, 20],
});
let icon3 = L.icon({
    iconUrl: 'images/legend/3.gif',
    iconSize: [20, 20],
});
let icon4 = L.icon({
    iconUrl: 'images/legend/4.gif',
    iconSize: [20, 20],
});

// localStorage.removeItem('allPos')
if (localStorage.getItem('allPos')) {

} else {
    localStorage.setItem('allPos', JSON.stringify(allPos))
}

//险情信息
let d = new Date();
let nowMonth = d.getMonth() + 1;
nowMonth < 10 ? nowMonth = "0" + nowMonth : 1;
let nowDay = d.getFullYear() + "-" + nowMonth + "-" + d.getDate();

function getPreMonth(date) {
    let arr = date.split('-');
    let year = arr[0]; //获取当前日期的年份
    let month = arr[1]; //获取当前日期的月份
    let day = arr[2]; //获取当前日期的日
    let days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中月的天数
    let year2 = year;
    let month2 = parseInt(month) - 1;
    if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
    }
    let day2 = day;
    let days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    let t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
}

let preMonth = getPreMonth(nowDay);

class DangerInfo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            info: {}
        }
    }

    componentDidMount() {
        let queries = "sdate=" + preMonth + "&edate=" + nowDay;
        superagent
            // .get('http://218.2.110.166:9090/njxc_cms/queryDangerInfo!Public')
            .get('http://10.32.224.47:9090/njxc_cms/queryDangerInfo!Public')
            .use(jsonp)
            .query(queries)
            .end(function (err, res) {
                if (res) {
                    this.setState({info: res.body.data})
                }
            }.bind(this))
    }

    render() {
        let dangerItem = []
        for (let i in this.state.info) {
            if (i < 6) {
                dangerItem.push(
                    <div className="dangerItem" key={i}>
                        <img src="images/danger.png" alt=""/>
                        {this.state.info[i].date} {this.state.info[i].address}发现 {this.state.info[i].ResName} {this.state.info[i].typename}
                    </div>
                )
            }

        }
        return (
            <div className="dangerInfo">
                {dangerItem}
                <div className="dangerBottom">
                    {preMonth} 至 {nowDay} 报送 {dangerItem.length} 条险情
                </div>
            </div>
        )
    }

}

class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            isoData: {},
            channelData: {},
            allPos: allPos
        };

    }

    componentDidMount = () => {
        try {
            this.setState({
                allPos: JSON.parse(localStorage.getItem('allPos'))
            })
        } catch (err) {

        }

        map = L.map('map', {zoomControl: false}).setView(position, 9);
        let self = this
        getData(self, map);
        setInterval(function () {
            getData(self, map);
        }, 300000);
        map.dragging.disable();
        map.touchZoom.disable();

        map.doubleClickZoom.disable();

        map.scrollWheelZoom.disable();

        // L.marker([31.72663, 119.05920], {icon: icon1}).addTo(map);

        L.esri.tiledMapLayer({
            // url: 'http://10.32.224.54:6080/arcgis/rest/services/%E5%8D%97%E4%BA%AC%E6%B0%B4%E5%8A%A1%E5%B1%80%E7%94%B5%E5%AD%90%E5%9C%B0%E5%9B%BE/%E5%8D%97%E4%BA%AC%E9%AB%98%E4%BA%AE%E5%9C%B0%E5%9B%BE/MapServer',
            url: 'http://122.227.159.86:6080/arcgis/rest/services/%E5%8D%97%E4%BA%AC%E9%98%B2%E6%B1%9B/%E5%8D%97%E4%BA%AC%E9%AB%98%E4%BA%AE%E5%9C%B0%E5%9B%BE102100/MapServer',
            maxZoom: 15,
            minZoom: 7,
            attribution: '&copy; 2017 弘泰水利'
        }).addTo(map);


        // L.marker([ 32.04, 118.78 ]).addTo(map).bindPopup(
        // '宁波').openPopup();

        // let nbMarker = L.circleMarker([32.04, 118.78], {
        //     radius: 4,
        //     fillColor: 'red',
        //     fillOpacity: 1,
        //     stroke: true,
        //     color: 'black',
        //     weight: 2
        // }).addTo(map);


    }


    handleStop = (e, data) => {
        let target = document.getElementById(data.node.id);
        let changePos = JSON.parse(localStorage.getItem('allPos'))
        for (let ii in changePos) {
            if (ii == data.node.id) {
                changePos[ii] = {}
                changePos[ii].left = target.offsetLeft + data.x;
                changePos[ii].top = target.offsetTop + data.y;
            }
        }
        localStorage.setItem('allPos', JSON.stringify(changePos));

    }

    render() {

        return (
            <Spin spinning={this.state.loading} tip="加载中...">
                <div className="mainWrap">
                    <div className="pageTitle">
                        南京市防汛大数据分析展示平台
                    </div>
                    <div className="pageHome">
                        <Draggable onStop={this.handleStop}>
                            <div className="mapArea" id="mapArea">
                                <div className="mapLegend">
                                    <div className="mapLegendItem">
                                        <img src="images/legend/1.png" alt=""/>
                                        雨强(1小时雨量大于16.7mm)
                                    </div>
                                    <div className="mapLegendItem">
                                        <img src="images/legend/2.png" alt=""/>
                                        河道水位超警戒
                                    </div>
                                    <div className="mapLegendItem">
                                        <img src="images/legend/3.png" alt=""/>
                                        中型水库水位超汛限
                                    </div>
                                    <div className="mapLegendItem">
                                        <img src="images/legend/4.png" alt=""/>
                                        积水大于20cm
                                    </div>
                                </div>
                                <div id="map" style={mapStyle}></div>
                                <div id="alertCircle">

                                </div>
                            </div>
                        </Draggable>
                        {/*气象信息*/}
                        <Draggable onStop={this.handleStop}>
                            <div className="total graphic selfGraphic" id="totalWrap">
                                <div className="selfTitle">
                                    气象信息
                                </div>
                                <Weather info={this.state.weather}/>
                                <div className="graphicRight"></div>
                                <div className="graphicLeft"></div>
                            </div>
                        </Draggable>
                        {/*降雨信息*/}
                        <Draggable onStop={this.handleStop}>
                            <div className="rain graphic" id="mainWrap">
                                <div className="selfTitle">
                                    降雨信息
                                </div>
                                <RainTop info={this.state.njRain}/>
                                <div className="clearfix">
                                    <div id="rain" className="fl"></div>
                                    <Isosurface info={this.state.isoData}/>
                                </div>
                                <div className="graphicRight"></div>
                                <div className="graphicLeft"></div>
                            </div>
                        </Draggable>
                        {/*长江水位流量*/}
                        <Draggable onStop={this.handleStop}>
                            <div className="graphic waterLever" id="waterLevelWrap">
                                <div className="selfTitle">
                                    长江水位流量
                                </div>
                                <p id="waterLevelTop"></p>
                                <p id="waterLevelBottom"></p>
                                <div id="waterLevel"></div>
                                <div className="graphicRight"></div>
                                <div className="graphicLeft"></div>
                            </div>
                        </Draggable>
                        {/*河道水位*/}
                        <Draggable onStop={this.handleStop}>
                            <div className="graphic waterChannel" id="waterChannelWrap">
                                <div className="selfTitle">
                                    河道水位
                                </div>
                                <WaterChannel info={this.state.channelData}/>
                                <div className="graphicRight"></div>
                                <div className="graphicLeft"></div>
                            </div>
                        </Draggable>
                        {/*泵站工情*/}
                        <Draggable onStop={this.handleStop}>
                            <div className="pump graphic" id="pumpWrap">
                                <div className="selfTitle">
                                    机泵流量统计
                                </div>
                                <div className="subTitle">
                                    泵站信息
                                </div>
                                <div className="clearfix mt10">
                                    <div className="fl">
                                        <div id="pump"></div>
                                        <p id="pumpP"></p>
                                    </div>
                                    <div className="fr">
                                        <div id="pumpRight"></div>
                                        <p id="pumpRightp"></p>
                                    </div>
                                </div>
                                <div className="mt10 floodPointWrap">
                                    <div className="subTitle">
                                        积淹点信息
                                    </div>
                                    <div className="clearfix">
                                        <div id="floodPoint" className="fl"></div>
                                        <div className="fr" id="floodPointRight"></div>
                                    </div>

                                </div>
                                <div className="graphicRight"></div>
                                <div className="graphicLeft"></div>
                            </div>
                        </Draggable>
                        <Draggable onStop={this.handleStop}>
                            <div className="graphic reservoir" id="reservoirWrap">
                                <div className="selfTitle">
                                    水库水位
                                </div>
                                <div className="reservoirLegend">
                                    <div className="lvlItem">
                                        <span style={{background: "#fc9c13"}}></span>
                                        水库超汛限水位
                                    </div>
                                    <div className="lvlItem">
                                        <span style={{background: "#17a6ca"}}></span>
                                        水库未超汛限水位
                                    </div>
                                </div>
                                <div id="reservoir"></div>
                                <div className="graphicRight"></div>
                                <div className="graphicLeft"></div>
                            </div>
                        </Draggable>
                        {/*应急响应*/}
                        <Draggable onStop={this.handleStop}>
                            <div className="graphic emergency" id="emergencyWrap">
                                <div className="selfTitle">
                                    应急响应
                                </div>
                                <Emergency info={this.state.emergency}/>
                                <div className="graphicRight"></div>
                                <div className="graphicLeft"></div>
                            </div>
                        </Draggable>

                        {/*险情信息*/}
                        <Draggable onStop={this.handleStop}>
                            <div className="graphic danger" id="dangerWrap">
                                <div className="selfTitle">险情信息</div>
                                <DangerInfo />
                                <div className="graphicRight"></div>
                                <div className="graphicLeft"></div>
                            </div>
                        </Draggable>
                    </div>
                </div>
            </Spin>
        )
    }
}

export default Home;
